package data

import (
	"context"
	"errors"
	userV1 "shop-demo/api/user/v1"
	"shop-demo/app/shop/admin/internal/biz"
)

type userRepo struct {
	data *Data
}

func NewUserRepo(data *Data) biz.UserRepo {
	return &userRepo{
		data: data,
	}
}

func (u *userRepo) CreateUser(ctx context.Context, user *biz.User) (*biz.User, error) {
	userReply, err := u.data.userClient.CreateUser(ctx, &userV1.CreateUserReq{
		Username: user.Username,
		Password: user.Password,
	})
	if err != nil {
		return nil, err
	}
	return &biz.User{
		Id:       userReply.Id,
		Username: userReply.Username,
	}, nil
}

func (u *userRepo) VerifyPassword(ctx context.Context, user *biz.User) (*biz.User, error) {
	reply, err := u.data.userClient.VerifyPassword(ctx, &userV1.VerifyPasswordReq{
		Username: user.Username,
		Password: user.Password,
	})
	if err != nil {
		return nil, err
	}

	if reply.Ok {
		return &biz.User{Id: reply.Id}, nil
	}

	return nil, errors.New("username or password is not right")
}

func (u *userRepo) GetUser(ctx context.Context, id int64) (*biz.User, error) {
	user, err := u.data.userClient.GetUser(ctx, &userV1.GetUserReq{Id: id})
	if err != nil {
		return nil, err
	}
	return &biz.User{
		Id:       user.Id,
		Username: user.Username,
	}, nil
}
